class Database {
  _dbName = 'aiChat'
  _dbVersion = 1
  _db: any = null

  constructor() {
    this.openDatabase()
  }

  // 打开数据库
  openDatabase() {
    return new Promise((resolve, reject) => {
      if (this._db) {
        resolve(this._db)
      } else {
        const request = indexedDB.open(this._dbName, this._dbVersion)
        request.onsuccess = (event: any) => {
          this._db = event.target.result
          console.log(this._db);
          console.log('Database opened successfully')
          resolve(this._db)
        }
        request.onupgradeneeded = (event: any) => {
          const db = event.target.result;
          db.createObjectStore('chats', { keyPath: 'id' });
          const constentsStore = db.createObjectStore('contents', { keyPath: 'id' });
          constentsStore.createIndex("chatId", "chatId", { unique: false });
        }
        request.onerror = (event: any) => {
          console.error('Database error: ' + event.target.errorCode)
          reject()
        }
      }
    })
  }

  // 添加数据
  addData(storeName: string, data: any) {
    console.log('add', { ...data });
    const transaction = this._db.transaction([storeName], 'readwrite')
    const objectStore = transaction.objectStore(storeName)

    return new Promise((resolve, reject) => {
      if (!data.id) {
        data.id = Date.now() + ''
      }
      const request = objectStore.add({ ...data })

      request.onsuccess = (event: any) => {
        resolve(data)
      }

      request.onerror = (event: any) => {
        reject('Error adding data: ' + event.target.errorCode)
      }
    })
  }

  // 更新数据
  updateData(storeName: string, data: any) {
    console.log('update', { ...data });
    const transaction = this._db.transaction([storeName], 'readwrite')
    const objectStore = transaction.objectStore(storeName)

    return new Promise((resolve, reject) => {
      const data2 = { ...data }
      delete data2.children // 劫持的字段会报错
      const request = objectStore.put(data2)

      request.onsuccess = (event: any) => {
        resolve(data)
      }

      request.onerror = (event: any) => {
        reject('Error updating data: ' + event.target.errorCode)
      }
    })
  }

  // 删除数据
  deleteData(storeName: string, key: string) {
    const transaction = this._db.transaction([storeName], 'readwrite')
    const objectStore = transaction.objectStore(storeName)

    return new Promise((resolve, reject) => {
      const request = objectStore.delete(key)

      request.onsuccess = (event: any) => {
        resolve(key)
      }

      request.onerror = (event: any) => {
        reject('Error deleting data: ' + event.target.errorCode)
      }
    })
  }

  // 清除数据
  deleteBatch(storeName: string, validate: Function) {
    const transaction = this._db.transaction([storeName], 'readwrite')
    const objectStore = transaction.objectStore(storeName)

    return new Promise((resolve, reject) => {
      const request = objectStore.openCursor();

      request.onsuccess = (event: any) => {
        const cursor = event.target.result
        if (cursor) {
          if (validate(cursor.value)) {
            objectStore.delete(cursor.key)
          }
          cursor.continue()
        }
        resolve('')
      }

      request.onerror = (event: any) => {
        reject('Error deleting data: ' + event.target.errorCode)
      }
    })
  }

  // 查询数据
  async getData(storeName: string, key: string) {
    await this.openDatabase()
    const transaction = this._db.transaction([storeName], 'readonly')
    const objectStore = transaction.objectStore(storeName)

    return new Promise((resolve, reject) => {
      const request = objectStore.get(key)

      request.onsuccess = (event: any) => {
        resolve(request.result)
      }

      request.onerror = (event: any) => {
        reject('Error getting data: ' + event.target.errorCode)
      }
    })
  }

  // 查询数据
  async listData(storeName: string) {
    await this.openDatabase()
    const transaction = this._db.transaction([storeName], 'readonly')
    const objectStore = transaction.objectStore(storeName)

    return new Promise((resolve, reject) => {
      const request = objectStore.getAll()

      request.onsuccess = (event: any) => {
        resolve(request.result)
      }

      request.onerror = (event: any) => {
        reject('Error getting data: ' + event.target.errorCode)
      }
    })
  }

  // 查询数据
  async queryData(storeName: string, index: string, key: string | number) {
    await this.openDatabase()
    const transaction = this._db.transaction([storeName], 'readonly')
    const objectStore = transaction.objectStore(storeName)
    const queryIndex = objectStore.index(index)

    return new Promise((resolve, reject) => {
      const request = queryIndex.getAll(key)

      request.onsuccess = (event: any) => {
        resolve(request.result)
      }

      request.onerror = (event: any) => {
        reject('Error getting data: ' + event.target.errorCode)
      }
    })
  }

  // 关闭数据库
  closeDatabase() {
    this._db.close()
    console.log('Database connection closed')
  }
}

const database = new Database()

export default database
